<template>
	<view class="container index">
		<!-- 头部导航 -->
		<nav-bar backState="2000" bgColor="#4c8aed" title="陪诊小程序" />
		<scroll-view
			class="list-scroll-content"
			:style="{height:`calc(100vh - ${titleBar}px)`}"
			scroll-y
			:refresher-triggered="!isLoad"
			:refresher-enabled="true"
			@refresherrefresh="loadData('refresh')"
			@scrolltolower="loadData"
		>
		<view class="pure_top"><h-icon class-name="ico_nav" src="nav_bg2" type="jpg" mode="heightFix"></h-icon></view>
		<swiper class="swiper"
			:indicator-dots="true"
			indicator-color="rgba(0, 0, 0, 0.5)"
			indicator-active-color="#4083F0"
			:autoplay="true"
			:interval="3000"
			:duration="500">
			<swiper-item v-for="(item,index) in bannerList" :key="index">
				<view class="swiper-item uni-bg-red">
					<image class="img" :src="item.imageUrl"></image>
				</view>
			</swiper-item>
		</swiper>
		<view class="index_banner">
			<view class="item">
				<image class="b_bg" :src="require('/staic/icon/ban1.png')" />
				<view class="text">一键陪诊</view>
			</view>
			<view class="item">
				<image class="b_bg" :src="require('/staic/icon/ban2.png')" />
				<view class="text">智能导诊</view>
			</view>
		</view>
		<!-- 瀑布流导航 -->
		<view class="tit-bar"><text class="blod">附近医院</text></view>
		<!-- 空白页 -->
		<view v-if="isEmpty||isAwait" class="empty" :style="{minHeight:`calc(100vh - 400rpx - ${titleBar}px)`}">
			<empty v-if="isEmpty" class="cont" :tips="hasLogin?'当前无订单，去下单吧…':'您还未登录,去登录吧'">
				<view class="btn-link" @click="openActionsheet">{{hasLogin?'一键下单':'去登录'}}</view>
			</empty>
			<empty v-if="isAwait" class="cont" tips="暂无数据" src="empty/await" />
		</view>
		<view v-if="!isEmpty&&!isAwait" class="goods-list">
			<view v-for="(item, index) in goodsList" :key="index">
				<order-card :item="item" @onConfim="loadData('refresh')">
					<template slot="pay">
						<text class="btn-cancel" @click="showPayPop(item)">去付款</text>
					</template>
					<template slot="quxiao">
						<text class="btn-cancel" @click="showcancelOrder(item,1)">取消订单</text>
					</template>
					<template slot="xieshang">
						<text class="btn-cancel" @click="showcancelOrder(item,2)">协商完成</text>
					</template>
				</order-card>
			</view>
			<view v-if="isOrderLine&&isLoad" class="btn-link" @click="openActionsheet">一键下单</view>
		</view>
	
		<!-- <uni-load-more v-if="!isEmpty&&!isAwait" :status="loadingType"></uni-load-more> -->
		</scroll-view>
		<uni-actionsheet :show="popData.isShow" :showHead="false" @close="onConfirmSelect">
			<view class="drawer">
				<view class="cont-box">
					<view class="pop-head">{{popData.title}}</view>
					<view
						v-for="(Item,Index) in popData.actions"
						:key="Index"
						class="li b-b"
						@click="chooseHandler(Index+1)"
					>
						{{Item.name}}
					</view>
					<view class="cancel" @click="onConfirmSelect">取消</view>
				</view>
			</view>	
		</uni-actionsheet>
		<pay-pop ref="payPicker" :order-id="orderId" :margin="margin" @onConfirm="loadData('refresh')" />
		<cancel-order ref="cancelOrder" :order-id="cancelOrderId" :type="cancelType" @onConfirm="loadData('refresh')" />
		<!-- <uni-pop
			type="confirm"
			v-model="popData2.isShow"
			:title="popData2.title">
			<template slot="commit">
				<button
				class="commit-btn yes"
				@click="subscribeMessage">订阅授权</button>
			</template>
		</uni-pop> -->
	</view>
</template>
<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
	import orderCard from '@/components/card/order-card.vue'
	import payPop from "@/components/pay-pop.vue"
	import CancelOrder from '@/components/cancel-order.vue';
	import { mapState } from 'vuex';
	var audio = wx.getBackgroundAudioManager()
	export default {
		components: {
			uniLoadMore,
			orderCard, // 猜你喜欢 - 商品卡片
			payPop,
			CancelOrder // 支付弹窗
		},
		options: { styleIsolation: 'shared' },
		data() {
			return {
				timer:null,
				popData:{
					isShow:false,
					title: '选择类型',
					actions:[
						{ name: '水电维修/家政保洁' },
						{ name: '电器维修' }
					]
				}, // 弹窗信息
				popData2:{},
				goodsList: [],
				params:{
					pageNum: 1,
					pageSize: 10
				},
				isLoad: false,
				loadingType: 'more', //加载更多状态
				titleBar: null, //导航高度
				bannerList:[], // 轮播
				cancelType:1,//1 取消订单 2 协商完成 改成水电1 电器2
				cancelOrderId:'',//取消orderId
				orderId:'', // 支付orderId
				margin: false, // 支付类型 是否是保证金
				loginUrl: '/pages/public/login', // 登录地址
				orderList:[], //轮询
				qingjishiyanshou:[],
				keyifukuanle:[],
				weixiuqingdanqueren:[]
			}
		},
		computed: {
			...mapState(['hasLogin','userInfo']),
			isEmpty() {
				return this.isLoad && this.goodsList.length === 0
			},
			isAwait(){
				let isAwait = false
				if(this.goodsList.length==1&&this.goodsList[0].status == 1){
					isAwait = true
				}
				return isAwait
			},
			isOrderLine(){ 
				return !this.goodsList.filter(item=>(item.status!=15)).length
			}
		},
		watch:{
			// hasLogin(newVal){
			// 	this.loadData('refresh') // 列表
			// }
		},
		onLoad(){
			this.titleBar = this.titleBarHeight
			this.getStatus()
		},
		onShow(){
			getApp().globalData.orderRefresh = true // 是否刷新
			uni.showTabBar()
			this.getBanner() // 轮播
			if(this.hasLogin) {
				this.timer = setInterval(() => {
					setTimeout(() => {
						this.getStatus()
					},0)
				},3000)
				this.subscribeMessage()
			} else {
				this.isLoad=true
				this.goodsList=[]
			}
		},
		onHide(){
			clearInterval(this.timer)
		},
		methods: {
			subscribeMessage(){
				// this.popData2.isShow = false
				// _this.popData2 = {
				// 				isShow: true,
				// 				title:`请允许订阅消息授权，订单消息会第一时间通知您`
				// 			}
				//需要订阅的消息模板，在微信公众平台手动配置获取模板ID
				let message = 'j7uy4vb_E2LKJZnxSgZc5zmhfxYH1gSfmul-ZZNTIhA'
				//如果总是拒绝（subscriptionsSetting，2.10.1库才支持）
				wx.getSetting({
					withSubscriptions: true,//是否同时获取用户订阅消息的订阅状态，默认不获取
					success: (res)=> {
						let setting = res.subscriptionsSetting
						if ((setting&& setting.itemSettings &&setting.itemSettings[message] == "reject")||!setting.mainSwitch){
							//打开设置去设置
							this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
						}else {
							wx.requestSubscribeMessage({
								tmplIds: [message],
								success: (res)=> {
									if (res[message] == 'accept'){
										this.$api.msg('订阅成功')
									}
								},
								fail: (res)=> { console.info(res) },
							})
						}
					}
				})
			},
			//打开设置
			openConfirm(message) {
				console.log(112)
				wx.showModal({
					content: message,
					confirmText: "确认",
					cancelText: "取消",
					success: (res) => {
						//点击“确认”时打开设置页面
						if (res.confirm) {
							wx.openSetting({
								success: (res) => {
									console.log(res.authSetting)
									this.popData2.isShow = false
								},
								fail: (error) => {
									console.log(error)
								}
							})
						} else {
							console.log('用户点击取消')
						}
					}
				});
			},
			player(name) {
        audio.title = '消息'
        audio.src = `http://su.techwells.com/audio/${name}.mp3`
      },
			async getStatus(){
				const { code,result } = await this.$apis.getApi('/order/pollingOrderList',{})
				if(code==200&&result){
					let arr = [...this.goodsList.map(item=>(item.orderId)),...result.map(item=>(item.orderId))]
					let arrLen = [...new Set(arr)].length
					if(this.orderList.length<result.length||arrLen!=this.goodsList.length){
						this.loadData('refresh') // 列表
					} else if(!result.length) {
						this.isLoad = true
						this.goodsList = []
						return
					}
					if(this.goodsList.length){
						this.goodsList.map((item,index)=>{
							this.filterStatus(result,item,index)
						})
					} else {
						this.filterStatus(result)
					}
					this.orderList = result
				}
			},
			filterStatus(result,item,index){
				result.map(it=>{
					if(it.status==6&&this.weixiuqingdanqueren.indexOf(it.orderId)==-1){
						this.weixiuqingdanqueren.push(it.orderId)
						this.player('weixiuqingdanqueren')
					} else if(it.status==10&&this.qingjishiyanshou.indexOf(it.orderId)==-1){
						this.qingjishiyanshou.push(it.orderId)
						this.player('qingjishiyanshou')
					} else if(it.status==11&&this.keyifukuanle.indexOf(it.orderId)==-1){
						this.keyifukuanle.push(it.orderId)
						this.player('keyifukuanle')
					}
					if(item&&it.orderId == item.orderId){
						this.goodsList[index].status = it.status
					}
				})
			},
			// 支付
			showPayPop(item) {
				this.orderId = item.orderId
				this.margin = item.status==13
				this.$refs.payPicker.showPicker();
			},
			showcancelOrder(item,type) {
				this.cancelOrderId = item.orderId
				this.cancelType = type
				this.$refs.cancelOrder.showPicker();
			},
			openActionsheet(){
				if(!this.hasLogin){
						uni.navigateTo({ url:this.loginUrl })
				} else {
					// wx.showActionSheet({
					// 	itemList: ['水电维修/家政保洁', '电器维修'],
					// 	success (res) {
					// 		console.log(res.tapIndex)
					// 	},
					// 	fail (res) {
					// 		console.log(res.errMsg)
					// 	}
					// })
					this.popData.isShow = true
					uni.hideTabBar()
				}
			},
			onConfirmSelect() {
				this.popData.isShow = false
				setTimeout(()=>{
					uni.showTabBar()
				},100)
			},
			chooseHandler(type){
				uni.navigateTo({ url:'/userPages/onlineOrder?fixType='+type })
				setTimeout(()=>{
					this.onConfirmSelect()
				},100)
			},
			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type='add') {
				if(type=='refresh') { // 初始化刷新
					this.isLoad = false
					this.params.pageNum = 1
					this.loadingType = 'more'
					this.goodsList = []
				}
				//没有更多直接返回
				if (this.loadingType==='loading' || this.loadingType==='nomore') return
				this.getGoodList()
				if(type === 'refresh'){
					uni.stopPullDownRefresh();
				}
			},
			async getGoodList() { // 猜你喜欢
				this.loadingType = 'loading'
				const { code,result } = await this.$apis.getApi('/order/orderList',{isToday:'1'})
				this.isLoad = true
				if(code==200) {
					// const { list,navigateLastPage,pageNum } = data.productMapList
					this.goodsList = result
					this.loadingType = 'nomore'
					//判断是否还有下一页，有是more  没有是nomore(测试数据判断大于20就没有了)
					// this.loadingType = pageNum >= navigateLastPage ? 'nomore' : 'more';
					// this.params.pageNum++
				} else {
					this.loadingType = 'nomore'
					this.goodsList = []
				}
			},
			async getBanner() {
				const { code,result } = await this.$apis.getApi('/user/getBannerList',{bannerType:'1'})
				if(code==200){
					this.bannerList = result
				}
				console.log(result)
			}
		}
	}
</script>
<style lang="scss" scoped>
@import "./index.scss";
.drawer{
	font-size: 28upx;
	text-align: center;
	.cont-box{
		.li{
			height: 98upx;
			font-size: 36upx;
			position: relative;
			margin: 0 24upx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 400;
		}
		.cancel{
			@extend .li;
			border-top: 20upx solid #F4F4F4;
			color: #DD0717;
			font-size: 34upx;
			margin: 0;
			height: 120upx;
		}
	}
	.pop-head{
		font-size: 34upx;
		font-weight: 500;
		padding: 16upx 0 36upx;
	}
}
</style>
